package com.ilearn.iodata.iolingo.service;

import com.ilearn.iodata.iolingo.utils.OlingoUtil;
import org.apache.olingo.commons.api.data.Entity;
import org.apache.olingo.commons.api.data.Property;
import org.apache.olingo.commons.api.data.ValueType;
import org.apache.olingo.commons.api.edm.EdmKeyPropertyRef;
import org.apache.olingo.commons.api.ex.ODataRuntimeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.net.URISyntaxException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.List;

@Service
public class GetCollectionService {

    @Autowired
    ApiKeysService apiKeysService;

    @Autowired
    JdbcTemplate jdbcTemplate;


    public List<Entity> getCollectionByJdbcTemplate(String sqlStatement, String entitySetName, List<EdmKeyPropertyRef> keyPropertyRefs) {
        System.out.println("sqlStatment:" + sqlStatement);

        return jdbcTemplate.query(sqlStatement, new RowMapper<Entity>() {
            @Nullable
            @Override
            public Entity mapRow(ResultSet resultSet, int i) throws SQLException {
                Entity entity = new Entity();
                ResultSetMetaData rsmd = resultSet.getMetaData();
                int count = rsmd.getColumnCount(); //求的有几个字段的意思
                for (i = 1; i <= count; i++) {

                    String key = rsmd.getColumnLabel(i);
                    Object value = resultSet.getObject(i);

                    Property property = new Property(null, key, ValueType.PRIMITIVE, value);

                    entity.addProperty(property);
                }
                OlingoUtil.createId(entitySetName, entity, keyPropertyRefs);
                return entity;
            }
        });
    }


    public Integer getCollectionCountByJdbcTemplate(String sqlStatement) {
        System.out.println("sqlStatment:" + sqlStatement);
        Integer count = jdbcTemplate.queryForObject(sqlStatement, Integer.class);
        return count;
    }
}
